package com.kc.data.scenic.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.gson.Gson;
import com.kc.data.common.annotation.Log;
import com.kc.data.common.annotation.RepeatSubmit;
import com.kc.data.common.base.StringUtils;
import com.kc.data.common.core.AjaxResult;
import com.kc.data.common.core.controller.BaseController;
import com.kc.data.common.domain.form.BizGoodsSpecsForm;
import com.kc.data.common.domain.goodsSku.BizGoodsSkuSpecs;
import com.kc.data.common.domain.goodsSku.BizGoodsSkuSpecsInfo;
import com.kc.data.common.domain.model.*;
import com.kc.data.common.enums.BusinessType;
import com.kc.data.common.page.TableDataInfo;
import com.kc.data.common.service.*;
import com.kc.data.common.utils.ImagesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品管理
 */
@RestController
@RequestMapping("/business/goods")
public class BizGoodsController extends BaseController {
    @Autowired
    private IBizGoodsService goodsService;
    @Autowired
    private IBizGoodsRelationCategoryService relationCategoryService;
//    @Resource
//    private BizGoodsSkuSpecsMapper bizGoodsSkuSpecsMapper;
//    @Resource
//    private BizGoodsSkuSpecsInfoMapper bizGoodsSkuSpecsInfoMapper;
    @Resource
    private IBizSetGoodsPriceService bizSetGoodsPriceService;
    @Resource
    private IBizScenicService bizScenicService;
    @Resource
    private IBizGoodsCategoryService goodsCategoryService;

    /**
     * 商品列表
     * @param bizGoods
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('business:goods:list')")
    @PostMapping("/list")
    public TableDataInfo getList(@RequestBody BizGoods bizGoods){
        startPage();
        Gson gson = new Gson();
        List<BizGoods> bizGoodsList = goodsService.getList(bizGoods);
        bizGoodsList.forEach(bizGoods1 -> {
            if(bizGoods1.getScenicName() == null){
                bizGoods1.setScenicName("");
            }
            if(bizGoods1.getMerchName() == null){
                bizGoods1.setMerchName("");
            }
            if(bizGoods1.getMarketBusinessName() == null){
                bizGoods1.setMarketBusinessName("");
            }
            String[] list = StringUtils.split(bizGoods1.getBannerList(),",");
            bizGoods1.setBannerListArr(list);
            String[] categoryIds = StringUtils.split(bizGoods1.getCategoryIds(),",");
            List<Integer> aftIdArray = new ArrayList();
            for(String id : categoryIds){
                aftIdArray.add(Integer.parseInt(id));
            }
            //Integer[] aftIdArray = (Integer[]) ConvertUtils.convert(categoryIds, Integer.class);
            bizGoods1.setGoodTypes(aftIdArray.toArray(new Integer[0]));
            bizGoods1.setContentImgArr(StringUtils.split(bizGoods1.getContentImg(),","));
        });
        return getDataTable(bizGoodsList);
    }

    //
    //@PreAuthorize("@ss.hasPermi('business:goods:selfSupportList')")
    @PostMapping("/selfSupportList")
    public TableDataInfo selfSupportList(@RequestBody BizGoods bizGoods){
        List<Map<String, Object>> selfSupportGoodsList = goodsService.selfSupportList(bizGoods);
        return getDataTable(selfSupportGoodsList);
    }

    /**
     * 商品新增
     * @param bizGoods
     * @return
     */
   // @PreAuthorize("@ss.hasPermi('business:goods:add')")
    @Log(title = "商品管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @RepeatSubmit
    @Transactional
    public AjaxResult add(@Validated @RequestBody BizGoods bizGoods) {
        if(!bizGoods.getEntryType().equals(0)){
            bizGoods.setAppCate(0);
        }
        if(bizGoods.getEntryType().equals(1)){
            bizGoods.setMerchid(bizGoods.getScenicId());
        }
        if(bizGoods.getVideoUrl() == null){
            bizGoods.setVideoUrl("");
        }
        if(bizGoods.getVideoImg() == null){
            bizGoods.setVideoImg("");
        }
        Map<String,Integer> map = null;
        try {
            map = ImagesUtils.getImgSize(bizGoods.getThumb());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(map == null){
            return AjaxResult.error();
        }
        if(bizGoods.getIsDelay() == null){
            bizGoods.setIsDelay(0);
        }
        if(bizGoods.getDelayDays() == null){
            bizGoods.setDelayDays(0);
        }
        bizGoods.setImgWidth(map.get("width"));
        bizGoods.setImgHeight(map.get("height"));
        //处理为可能null字段
        //处理商品轮播图end
        Gson gson = new Gson();
        String imageListStr = StringUtils.join(bizGoods.getBannerListArr(), ",");
        List<String> imageList = Arrays.asList(bizGoods.getBannerListArr());
        List<BizImageSize> imageSizeDTOList = new ArrayList<>();
        imageList.forEach(image->{
            try {
                Map<String,Integer> mapSize = ImagesUtils.getImgSize(image);
                imageSizeDTOList.add(new BizImageSize(image,mapSize.get("width"),mapSize.get("height")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        bizGoods.setBannerListAttr(gson.toJson(imageSizeDTOList));
        bizGoods.setBannerList(imageListStr);
        //处理商品轮播图start

        //todo 类别处理判断  如果归属类别不是平台，需要判断图片商品和视频商品，另外需要判断景区id或商家id
        if(!bizGoods.getEntryType().equals(0)){
            //非平台商品
            if(bizGoods.getContentType().equals(0)){
                //图片商品
            }else{
                //视频商品
                if(StringUtils.isEmpty(bizGoods.getVideoImg()) || StringUtils.isEmpty(bizGoods.getVideoUrl())){
                    return AjaxResult.error("参数错误");
                }
            }
            if(bizGoods.getEntryType().equals(1)){
                //景区
                if(bizGoods.getScenicId() == null || bizGoods.getScenicId().equals(0)){
                    return AjaxResult.error("参数错误");
                }
                //处理商家id信息
                BizScenic bizScenic = bizScenicService.getInfoById(bizGoods.getScenicId());
                bizGoods.setMerchid(bizScenic.getUserId());
            }else if(bizGoods.getEntryType() > 1){
                //景区
                if(bizGoods.getMerchid() == null || bizGoods.getMerchid().equals(0)){
                    return AjaxResult.error("参数错误");
                }
            }
        }


        //写入类别表
        //处理类别list
        bizGoods.setCategoryIds(StringUtils.join(bizGoods.getGoodTypes(), ","));
        bizGoods.setContentImg(StringUtils.join(bizGoods.getContentImgArr(),","));
        log.info("商品新增参数{}",bizGoods);
        Integer goodsId = goodsService.add(bizGoods);
        Integer[] cates = bizGoods.getGoodTypes();
        List<BizGoodsRelationCategory> goodsRelationCategoryList = Arrays.stream(cates).map(id->new BizGoodsRelationCategory(goodsId,id)).collect(Collectors.toList());
        relationCategoryService.add(goodsRelationCategoryList);
        return AjaxResult.success();
    }

    /**
     * 商品编辑
     * @param bizGoods
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('business:goods:edit')")
    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    @RepeatSubmit
    @Transactional
    public AjaxResult edit(@Validated @RequestBody BizGoods bizGoods) {
        if(!bizGoods.getEntryType().equals(0)){
            bizGoods.setAppCate(0);
        }
        if(bizGoods.getEntryType().equals(1)){
            bizGoods.setMerchid(bizGoods.getScenicId());
        }
        //todo 类别处理判断  如果归属类别不是平台，需要判断图片商品和视频商品，另外需要判断景区id或商家id
        if(!bizGoods.getEntryType().equals(0)){
            //非平台商品
            if(bizGoods.getContentType().equals(0)){
                //图片商品
            }else{
                //视频商品
                if(StringUtils.isEmpty(bizGoods.getVideoImg()) || StringUtils.isEmpty(bizGoods.getVideoUrl())){
                    return AjaxResult.error("参数错误");
                }
            }
            if(bizGoods.getEntryType().equals(1)){
                //景区
                if(bizGoods.getScenicId() == null || bizGoods.getScenicId().equals(0)){
                    return AjaxResult.error("参数错误");
                }
                //处理商家id信息
                BizScenic bizScenic = bizScenicService.getInfoById(bizGoods.getScenicId());
                bizGoods.setMerchid(bizScenic.getUserId());
            }else if(bizGoods.getEntryType() > 1){
                //非景区
                if(bizGoods.getMerchid() == null || bizGoods.getMerchid().equals(0)){
                    return AjaxResult.error("参数错误");
                }
            }
        }
        Map<String,Integer> map = null;
        try {
            map = ImagesUtils.getImgSize(bizGoods.getThumb());
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(map == null){
            return AjaxResult.error();
        }
        bizGoods.setImgWidth(map.get("width"));
        bizGoods.setImgHeight(map.get("height"));
        //写入类别表
        //处理类别list
        Integer goodsId =  bizGoods.getId();
        //处理商品轮播图start
        Gson gson = new Gson();
        String imageListStr = StringUtils.join(bizGoods.getBannerListArr(), ",");
        List<String> imageList = Arrays.asList(bizGoods.getBannerListArr());
        List<BizImageSize> imageSizeDTOList = new ArrayList<>();
        imageList.forEach(image->{
            try {
                Map<String,Integer> mapSize = ImagesUtils.getImgSize(image);
                imageSizeDTOList.add(new BizImageSize(image,mapSize.get("width"),mapSize.get("height")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        if(bizGoods.getIsDelay() == null){
            bizGoods.setIsDelay(0);
        }
        if(bizGoods.getDelayDays() == null){
            bizGoods.setDelayDays(0);
        }
        bizGoods.setBannerListAttr(gson.toJson(imageSizeDTOList));
        bizGoods.setBannerList(imageListStr);
        //处理商品轮播图end
        bizGoods.setCategoryIds(StringUtils.join(bizGoods.getGoodTypes(), ","));
        bizGoods.setContentImg(StringUtils.join(bizGoods.getContentImgArr(),","));
        goodsService.edit(bizGoods);
        Integer[] cates = bizGoods.getGoodTypes();
        List<BizGoodsRelationCategory> goodsRelationCategoryList = Arrays.stream(cates).map(id->new BizGoodsRelationCategory(goodsId,id)).collect(Collectors.toList());
        //删除记录
        relationCategoryService.delete(bizGoods.getId());
        //添加记录
        relationCategoryService.add(goodsRelationCategoryList);
        return AjaxResult.success();
    }

    /**
     * 商品 删除
     * @param id
     * @return
     */
   // @PreAuthorize("@ss.hasPermi('business:goods:remove')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove/{id}")
    public AjaxResult remove(@PathVariable Integer id){
        BizGoods bizGoods = new BizGoods();
        bizGoods.setId(id);
        bizGoods = goodsService.getInfo(bizGoods);
        if(bizGoods == null || StringUtils.isEmpty(bizGoods.getTitle())){
            return AjaxResult.success("操作失败，请稍后重试");
        }

        bizGoods.setIsDeleted(1);
        return AjaxResult.success(goodsService.delete(bizGoods));
    }

    /**
     * 设置商品规格
     * @param bizGoodsSpecsForm
     * @return
     */
//    @PreAuthorize("@ss.hasPermi('business:goods:specs')")
//    @Log(title = "商品管理", businessType = BusinessType.UPDATE)
//    @PutMapping("/specs")
//    @Transactional
//    public AjaxResult specs(@Validated @RequestBody BizGoodsSpecsForm bizGoodsSpecsForm) {
//        BizGoods bizGoods = new BizGoods();
//        bizGoods.setId(bizGoodsSpecsForm.getId());
//        //查找当前商品
//        bizGoods = goodsService.getInfo(bizGoods);
//        //商品规格处理
//        String specsString = JSONObject.toJSONString(bizGoodsSpecsForm.getSpecs());
//        Integer goodsId = bizGoodsSpecsForm.getId();
//        bizGoodsSkuSpecsMapper.deleteByGoodsId(goodsId);
//        bizGoodsSkuSpecsInfoMapper.deleteByGoodsId(goodsId);
//        for(BizGoodsSkuSpecsInfo goodsSkuSpecsInfo : bizGoodsSpecsForm.getSpecs()){
//            //先处理 BizGoodsSkuSpecs
//            //BizGoodsSkuSpecs(String name, Integer status, Integer goodsId)
//            String[] sku = StringUtils.split(goodsSkuSpecsInfo.getSku(),";");
//            //先去库里查，如果有，变更，如果没有，新增
//            BizGoodsSkuSpecs bizGoodsSkuSpecsSearch = new BizGoodsSkuSpecs();
//            bizGoodsSkuSpecsSearch.setName(sku[0]);
//            bizGoodsSkuSpecsSearch.setGoodsId(goodsId);
//            List<BizGoodsSkuSpecs> bizGoodsSkuSpecsList = bizGoodsSkuSpecsMapper.select(bizGoodsSkuSpecsSearch);
//            BizGoodsSkuSpecs bizGoodsSkuSpecs = new BizGoodsSkuSpecs(sku[0], 1, goodsId);
//            Integer specsId = 0;
//            bizGoodsSkuSpecs.setStatus(1);
//            if(bizGoodsSkuSpecsList.size() != 0){
//                //修改
//                bizGoodsSkuSpecs.setId(bizGoodsSkuSpecsList.get(0).getId());
//                bizGoodsSkuSpecsMapper.updateByPrimaryKey(bizGoodsSkuSpecs);
//            }else {
//                //新增
//                bizGoodsSkuSpecsMapper.insert(bizGoodsSkuSpecs);
//            }
//            specsId = bizGoodsSkuSpecs.getId();
//            //商品sku处理
//            BizGoodsSkuSpecsInfo bizGoodsSkuSpecsInfoSearch = new BizGoodsSkuSpecsInfo();
//            bizGoodsSkuSpecsInfoSearch.setGoodsId(goodsId);
//            bizGoodsSkuSpecsInfoSearch.setSpecsId(specsId);
//            if(sku.length > 1) {
//                bizGoodsSkuSpecsInfoSearch.setSkuName(sku[1]);
//            }else{
//                bizGoodsSkuSpecsInfoSearch.setSkuName(sku[0]);
//            }
//            List<BizGoodsSkuSpecsInfo> bizGoodsSkuSpecsInfoList = bizGoodsSkuSpecsInfoMapper.select(bizGoodsSkuSpecsInfoSearch);
//            //查询数据是否存在
//            String skuName = "";
//            if(sku.length > 1) {
//                skuName = sku[1];
//            }else{
//                skuName = sku[0];
//            }
//            BizGoodsSkuSpecsInfo bizGoodsSkuSpecsInfo = new BizGoodsSkuSpecsInfo(skuName,goodsSkuSpecsInfo.getActivityPrice(),goodsSkuSpecsInfo.getPrice(),goodsSkuSpecsInfo.getStock(),
//                    goodsSkuSpecsInfo.getImage(),goodsId,specsId);
//            bizGoodsSkuSpecsInfo.setSku("");
//            bizGoodsSkuSpecsInfo.setStatus(1);
//            bizGoodsSkuSpecsInfo.setSpecsName(sku[0]);
//            //状态标记为删除
//
//            if(bizGoodsSkuSpecsInfoList.size() == 0){
//                bizGoodsSkuSpecsInfoMapper.insert(bizGoodsSkuSpecsInfo);
//            }else{
//                bizGoodsSkuSpecsInfo.setId(bizGoodsSkuSpecsInfoList.get(0).getId());
//                bizGoodsSkuSpecsInfoMapper.updateByPrimaryKey(bizGoodsSkuSpecsInfo);
//            }
//        }
//        bizGoods.setSpecs(specsString);
//        String bigSpecsString = JSONObject.toJSONString(bizGoodsSpecsForm.getBigSpecs());
//        bizGoods.setBigSpecs(bigSpecsString);
//        return toAjax(goodsService.edit(bizGoods));
//    }

    /**
     * 获取商品规格
     * @param id
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('business:goods:getSpecs')")
    @Log(title = "商品管理", businessType = BusinessType.DELETE)
    @GetMapping("/getSpecs/{id}")
    public AjaxResult getSpecs(@PathVariable Integer id){
        BizGoods bizGoods = new BizGoods();
        bizGoods.setId(id);
        //查找当前商品
        bizGoods = goodsService.getInfo(bizGoods);
        //获取商品规格，转换成传参格式数据
        BizGoodsSpecsForm goodsSpecsForm = new BizGoodsSpecsForm();
        goodsSpecsForm.setId(id);
        List<BizGoodsSkuSpecsInfo> specs = JSONObject.parseObject(bizGoods.getSpecs(), new TypeReference<List<BizGoodsSkuSpecsInfo>>() {});
        goodsSpecsForm.setSpecs(specs);
        List<BizGoodsSkuSpecs> bigSpecs = JSONObject.parseObject(bizGoods.getBigSpecs(), new TypeReference<List<BizGoodsSkuSpecs>>() {});
        goodsSpecsForm.setBigSpecs(bigSpecs);
        if(goodsSpecsForm.getSpecs() == null){
            goodsSpecsForm.setSpecs(new ArrayList<>());
        }
        if(goodsSpecsForm.getBigSpecs() == null){
            goodsSpecsForm.setBigSpecs(new ArrayList<>());
        }
        return new AjaxResult(200,"操作成功",goodsSpecsForm);
    }

    /**
     * 根基成本价获取商品销售价
     * @return
     */
    //@PreAuthorize("@ss.hasPermi('business:goods:getSalePrice')")
    @PostMapping(value = "/getSalePrice/{constPrice}")
    public AjaxResult getSalePrice(@PathVariable("constPrice") Double constPrice){
        if(null == constPrice || constPrice<=0.0){
            return  AjaxResult.error("系统繁忙，请稍后重试");
        }
        BigDecimal salePrice = bizSetGoodsPriceService.getGoodsSalePriceByCost(constPrice);
        Map<String,BigDecimal> map = new HashMap<>();
        map.put("salePrice",salePrice);
        return new AjaxResult(200,"操作成功",map);
    }

    //@PreAuthorize("@ss.hasPermi('business:goodsCategory:list')")
    @GetMapping("/getCategorylist")
    public AjaxResult getCategorylist(BizGoodsCategory bizAppGoodsCategory){
        List<BizGoodsCategory> appGoodsCategoryList = goodsCategoryService.getList(bizAppGoodsCategory);
        return AjaxResult.success(goodsCategoryService.buildTypes(appGoodsCategoryList));
    }
}
